<?php 
if (!function_exists('jigoshop_variable_add_to_cart')) :
/**
 * Print Buy Section in single product page
 */
function jigoshop_variable_add_to_cart() {

	global $post, $_product;

	$attributes = $_product->get_available_attributes_variations();

    //get all variations available as an array for easy usage by javascript
    $variationsAvailable = array();
    $children = $_product->get_children();

    foreach($children as $child) {
        /* @var $variation jigoshop_product_variation */
        $variation = $_product->get_child( $child );
        if($variation instanceof jigoshop_product_variation && $variation->is_visible()) {
            $vattrs = $variation->get_variation_attributes();
            $availability = $variation->get_availability();

            //@todo needs to be moved to jigoshop_product_variation class
            if (has_post_thumbnail($variation->get_variation_id())) {
                $attachment_id = get_post_thumbnail_id( $variation->get_variation_id() );
                $large_thumbnail_size = apply_filters('single_product_large_thumbnail_size', 'shop_large');
                $image = current(wp_get_attachment_image_src( $attachment_id, $large_thumbnail_size));
                $image_link = current(wp_get_attachment_image_src( $attachment_id, 'full'));
            } else {
                $image = '';
                $image_link = '';
            }

			$a_weight = $a_length = $a_width = $a_height = '';

            if ( $variation->get_weight() ) {
            	$a_weight = '
                	<tr class="weight">
                		<th>Weight</th>
                		<td>'.$variation->get_weight().get_option('jigoshop_weight_unit').'</td>
                	</tr>';
        	}

        	if ( $variation->get_length() ) {
            	$a_length = '
                	<tr class="length">
                		<th>Length</th>
                		<td>'.$variation->get_length().get_option('jigoshop_dimension_unit').'</td>
                	</tr>';
            }

            if ( $variation->get_width() ) {
                $a_width = '
                	<tr class="width">
                		<th>Width</th>
                		<td>'.$variation->get_width().get_option('jigoshop_dimension_unit').'</td>
                	</tr>';
            }

            if ( $variation->get_height() ) {
                $a_height = '
                	<tr class="height">
                		<th>Height</th>
                		<td>'.$variation->get_height().get_option('jigoshop_dimension_unit').'</td>
                	</tr>
                ';
        	}

            $variationsAvailable[] = array(
				'variation_id'     => $variation->get_variation_id(),
				'sku'              => '<div class="sku">SKU: ' . $variation->get_sku() . '</div>',
				'attributes'       => $vattrs,
				'image_src'        => $image,
				'image_link'       => $image_link,
				'price_html'       => '<span class="price">' . __('Price: ', 'jigoshop') . $variation->get_price_html().'</span>',
				'availability_html'=> '<p class="stock ' . esc_attr( $availability['class'] ) . '">'. $availability['availability'].'</p>',
				'a_weight'         => $a_weight,
				'a_length'         => $a_length,
				'a_width'          => $a_width,
				'a_height'         => $a_height,
            );
        }
    }

	?>
    <script type="text/javascript">
        var product_variations = <?php echo json_encode($variationsAvailable) ?>;
    </script>
	<form action="<?php echo esc_url( $_product->add_to_cart_url() ); ?>" class="variations_form cart" method="post">
		<fieldset class="variations">
			<?php foreach ( $attributes as $name => $options ): ?>
				<?php $sanitized_name = sanitize_title( $name ); ?>
				<div>
					<span class="select_label"><?php echo jigoshop_product::attribute_label('pa_'.$name); ?></span>
					<select id="<?php echo esc_attr( $sanitized_name ); ?>" name="tax_<?php echo $sanitized_name; ?>">
						<option value=""><?php echo __('Choose an option ', 'jigoshop') ?>&hellip;</option>
						<?php foreach ( $options as $value ) : ?>
							<?php if ( taxonomy_exists( 'pa_'.$sanitized_name )) : ?>
								<?php $term = get_term_by( 'slug', $value, 'pa_'.$sanitized_name ); ?>
								<option value="<?php echo esc_attr( $term->slug ); ?>"><?php echo $term->name; ?></option>
							<?php else : ?>
								<option value="<?php echo esc_attr( sanitize_title( $value ) ); ?>"><?php echo $value; ?></option>
							<?php endif;?>
						<?php endforeach; ?>
					</select>
				</div>
            <?php endforeach;?>
		</fieldset>
		<div class="single_variation"></div>
		<?php do_action('jigoshop_before_add_to_cart_form_button'); ?>
		<div class="variations_button" style="display:none;">
            <input type="hidden" name="variation_id" value="" />
            <input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
            <p class="help"><?php echo __( 'Vui lòng chọn số lượng sản phẩm muốn đặt hàng', 'jigoshop' ); ?>:</p>
            <div class="buy-button">
                <div class="quantity"><input name="quantity" value="1" size="4" title="Qty" class="input-text qty text" maxlength="12" /></div>
    			<input type="submit" class="button-alt" value="<?php esc_html_e('Add to cart', 'jigoshop'); ?>" />
            </div>
		</div>
		<?php do_action('jigoshop_add_to_cart_form'); ?>
	</form>
	<?php
}
endif;


if (!function_exists('jigoshop_template_loop_add_to_cart_customize')) :
/**
 * Products Loop
 **/
function jigoshop_template_loop_add_to_cart_customize( $post, $_product ) {
    do_action('jigoshop_before_add_to_cart_button');

    // do not show "add to cart" button if product's price isn't announced
    if ( $_product->get_price() === '' AND ! ($_product->is_type(array('variable', 'grouped', 'external'))) ) 
        return;

    if ( $_product->is_in_stock() OR $_product->is_type('external') ) :
        if ( $_product->is_type(array('variable', 'grouped')) ) :
            $output = '<a href="'.get_permalink($_product->id).'" class="add-to-cart">'.__('Add to cart', 'jigoshop').'</a>';
        elseif ( $_product->is_type('external') ) :
            $output = '<a href="'.get_post_meta( $_product->id, 'external_url', true ).'" class="add-to-cart">'.__('Mua sản phẩm này', 'jigoshop').'</a>';
        else :
            $output = '<a href="'.esc_url($_product->add_to_cart_url()).'" class="add-to-cart">'.__('Add to cart', 'jigoshop').'</a>';
        endif;
    elseif ( ($_product->is_type(array('grouped')) ) ) :
        return;
    else :
        $output = '<span class="nostock">'.__('Hết hàng', 'jigoshop').'</span>';
    endif;

    echo $output;

    do_action('jigoshop_after_add_to_cart_button');

}
endif;


if (!function_exists('jigoshop_show_product_thumbnails_customize')) :
/**
 * Display thumbnail image in single product page
 */
function jigoshop_show_product_thumbnails_customize() {
    global $post;
    echo '<div class="thumb-container">';

    $thumb_id = get_post_thumbnail_id();
    $small_thumbnail_size = jigoshop_get_image_size( 'shop_tiny' );
    $large_thumbnail_size = jigoshop_get_image_size( 'shop_large' );
    $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID, 'orderby' => 'id', 'order' => 'asc' );

    $attachments = get_posts($args);
    if ($attachments) :
        $loop = 0;
        $columns = apply_filters( 'single_thumbnail_columns', 4 );
        foreach ( $attachments as $attachment ) :

                $loop++;

                $_post =  get_post( $attachment->ID );
                $url = wp_get_attachment_url($_post->ID);

                $post_title = esc_attr($_post->post_title);
                $image = wp_get_attachment_image($attachment->ID, $small_thumbnail_size);
                $large_url = wp_get_attachment_image_src($attachment->ID, $large_thumbnail_size);

                if ( ! $image || $url == get_post_meta($post->ID, 'file_path', true) )
                        continue;

                echo '<a href="'.esc_url($large_url[0]).'" title="'.esc_attr($post_title).'" rel="thumbnails" class="zoom ';
                if ($loop==1 || ($loop-1)%$columns==0) echo 'first';
                if ($loop%$columns==0) echo 'last';
                echo '">'.$image.'</a>';

        endforeach;
    endif;
    wp_reset_query();

    echo '</div>';
}
endif;



if (!function_exists('jigoshop_pagination_customize'))  :
/**
 * Print paging HTML
 */
function jigoshop_pagination_customize() {
    global $wp_query;
    global $paged;
    $pagedTmp = 0;
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;?>
    
    <?php if ($wp_query->max_num_pages > 1) : ?>
            <div id="paging" class="paging top">
                <div id="paging-meta">Đang xem trang thứ <?php echo $paged ?> trên <?php echo $wp_query->max_num_pages ?> trang</div>
    
                <div id="paging-items">
                    <?php previous_posts_link(__('Trang trước', 'jigoshop')); ?>
                    <?php 
                        $paged;
                        for ($pagedTmp = 1; $pagedTmp <= $wp_query->max_num_pages; $pagedTmp++) { 
                            if ($pagedTmp == $paged) {
                    ?>
                                <a href="#" class="current"><?php echo $paged; ?></a>
                    <?php
                            } else {
                    ?>
                                <a href="<?php echo add_query_arg('paged', $pagedTmp, "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]) ?>"><?php echo $pagedTmp; } ?></a>
                    <?php } ?>
                    <?php next_posts_link(__('Trang sau', 'jigoshop')); ?>
                </div>
            </div>
    <?php endif; 
}
endif;

/**
 * Jigoshop Breadcrumb
 **/
if (!function_exists('jigoshop_breadcrumb')) {
	function jigoshop_breadcrumb( $delimiter = ' &rsaquo; ', $wrap_before = '<div id="breadcrumb">', $wrap_after = '</div>', $before = '', $after = '', $home = null ) {

	 	global $post, $wp_query, $author, $paged;

	 	if( !$home ) $home = _x('Home', 'breadcrumb', 'jigoshop');

	 	$home_link = home_url();

	 	$prepend = '';

	 	if ( get_option('jigoshop_prepend_shop_page_to_urls')=="yes" && jigoshop_get_page_id('shop') && get_option('page_on_front') !== jigoshop_get_page_id('shop') )
	 		$prepend =  $before . '<a href="' . esc_url( jigoshop_cart::get_shop_url() ). '">' . get_the_title( jigoshop_get_page_id('shop') ) . '</a> ' . $after . $delimiter;


	 	if ( (!is_home() && !is_front_page() && !(is_post_type_archive() && get_option('page_on_front')==jigoshop_get_page_id('shop'))) || is_paged() ) :

			echo $wrap_before;

			echo $before  . '<a class="home" href="' . $home_link . '">' . $home . '</a> '  . $after . $delimiter ;

			if ( is_category() ) :

	      		$cat_obj = $wp_query->get_queried_object();
	      		$this_category = $cat_obj->term_id;
	      		$this_category = get_category( $this_category );
	      		if ($thisCat->parent != 0) :
	      			$parent_category = get_category( $this_category->parent );
	      			echo get_category_parents($parent_category, TRUE, $delimiter );
	      		endif;
	      		echo $before . single_cat_title('', false) . $after;

	 		elseif ( is_tax('product_cat') ) :

	 			//echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . ucwords(get_option('jigoshop_shop_slug')) . '</a>' . $after . $delimiter;

	 			$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

				$parents = array();
				$parent = $term->parent;
				while ($parent):
					$parents[] = $parent;
					$new_parent = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ));
					$parent = $new_parent->parent;
				endwhile;
				if(!empty($parents)):
					$parents = array_reverse($parents);
					foreach ($parents as $parent):
						$item = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ));
						echo $before .  '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . $item->name . '</a>' . $after . $delimiter;
					endforeach;
				endif;

	 			$queried_object = $wp_query->get_queried_object();
	      		echo $prepend . $before . $queried_object->name . $after;

	      	elseif ( is_tax('product_tag') ) :

	 			$queried_object = $wp_query->get_queried_object();
	      		echo $prepend . $before . __('Products tagged &ldquo;', 'jigoshop') . $queried_object->name . '&rdquo;' . $after;

	 		elseif ( is_day() ) :

				echo $before . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $after . $delimiter;
				echo $before . '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a>' . $after . $delimiter;
				echo $before . get_the_time('d') . $after;

			elseif ( is_month() ) :

				echo $before . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $after . $delimiter;
				echo $before . get_the_time('F') . $after;

			elseif ( is_year() ) :

				echo $before . get_the_time('Y') . $after;

	 		elseif ( is_post_type_archive('product') && get_option('page_on_front') !== jigoshop_get_page_id('shop') ) :

	 			$_name = jigoshop_get_page_id('shop') ? get_the_title( jigoshop_get_page_id('shop') ) : ucwords(get_option('jigoshop_shop_slug'));

	 			if (is_search()) :

	 				echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . $_name . '</a>' . $delimiter . __('Search results for &ldquo;', 'jigoshop') . get_search_query() . '&rdquo;' . $after;

	 			else :

	 				echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . $_name . '</a>' . $after;

	 			endif;

			elseif ( is_single() && !is_attachment() ) :

				if ( get_post_type() == 'product' ) :

	       			//echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . ucwords(get_option('jigoshop_shop_slug')) . '</a>' . $after . $delimiter;
	       			echo $prepend;

	       			if ($terms = get_the_terms( $post->ID, 'product_cat' )) :
						$term = current($terms);
						$parents = array();
						$parent = $term->parent;
						while ($parent):
							$parents[] = $parent;
							$new_parent = get_term_by( 'id', $parent, 'product_cat');
							$parent = $new_parent->parent;
						endwhile;
						if(!empty($parents)):
							$parents = array_reverse($parents);
							foreach ($parents as $parent):
								$item = get_term_by( 'id', $parent, 'product_cat');
								echo $before . '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . $item->name . '</a>' . $after . $delimiter;
							endforeach;
						endif;
						echo $before . '<a href="' . get_term_link( $term->slug, 'product_cat' ) . '">' . $term->name . '</a>' . $after . $delimiter;
					endif;

	        		echo $before . get_the_title() . $after;

				elseif ( get_post_type() != 'post' ) :
					$post_type = get_post_type_object(get_post_type());
	        		$slug = $post_type->rewrite;
	       			echo $before . '<a href="' . get_post_type_archive_link(get_post_type()) . '">' . $post_type->labels->singular_name . '</a>' . $after . $delimiter;
	        		echo $before . get_the_title() . $after;
				else :
					$cat = current(get_the_category());
					echo get_category_parents($cat, TRUE, $delimiter);
					echo $before . get_the_title() . $after;
				endif;

	 		elseif ( is_404() ) :

		    	echo $before . __('Error 404', 'jigoshop') . $after;

	    	elseif ( !is_single() && !is_page() && get_post_type() != 'post' ) :

				$post_type = get_post_type_object(get_post_type());
				if ($post_type) : echo $before . $post_type->labels->singular_name . $after; endif;

			elseif ( is_attachment() ) :

				$parent = get_post($post->post_parent);
				$cat = get_the_category($parent->ID); $cat = $cat[0];
				echo get_category_parents($cat, TRUE, '' . $delimiter);
				echo $before . '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a>' . $after . $delimiter;
				echo $before . get_the_title() . $after;

			elseif ( is_page() && !$post->post_parent ) :

				echo $before . get_the_title() . $after;

			elseif ( is_page() && $post->post_parent ) :

				$parent_id  = $post->post_parent;
				$breadcrumbs = array();
				while ($parent_id) {
					$page = get_page($parent_id);
					$breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
					$parent_id  = $page->post_parent;
				}
				$breadcrumbs = array_reverse($breadcrumbs);
				foreach ($breadcrumbs as $crumb) :
					echo $crumb . '' . $delimiter;
				endforeach;
				echo $before . get_the_title() . $after;

			elseif ( is_search() ) :

				echo $before . __('Search results for &ldquo;', 'jigoshop') . get_search_query() . '&rdquo;' . $after;

			elseif ( is_tag() ) :

	      		echo $before . __('Posts tagged &ldquo;', 'jigoshop') . single_tag_title('', false) . '&rdquo;' . $after;

			elseif ( is_author() ) :

				$userdata = get_userdata($author);
				echo $before . __('Author: ', 'jigoshop') . $userdata->display_name . $after;

		    endif;

			if ( get_query_var('paged') ) :

				echo ' (' . __('Page', 'jigoshop') . ' ' . get_query_var('paged') .')';

			endif;

	    	echo $wrap_after;
	    elseif ( get_option('page_on_front') == jigoshop_get_page_id('shop') ) :
	       echo $wrap_before . $before . $home . $after . $wrap_after;
		endif;

	}
}
